<template>
  <a-config-provider :locale="locale" :theme="themeConfig">
    <site-token>
      <router-view />
    </site-token>
  </a-config-provider>
</template>

<script lang="ts" setup>
import { computed, provide, ref, watch } from 'vue';
import { theme as antdTheme } from 'ant-design-vue';
import SiteToken from './components/site-token.vue';
import { STORAGE_LANG_KEY, useAppStore, STORAGE_REFRESH_TOKEN_KEY } from '@/store/app';
import { localStorage } from '@/utils/local-storage';
import useMediaQuery from '@/utils/hooks/useMediaQuery';
import { useI18n } from 'vue-i18n';
import useMenuState, { MenuStateSymbol } from './layouts/use-menu-state';
import { useMultiTabStateProvider } from './components/multi-tab';
import { defaultLang } from './locales';
import type { ConfigProviderProps } from 'ant-design-vue';
import { updateTheme } from '@/components/setting-drawer/util';
import { omit } from 'lodash-es';
import { refreshToken } from '@/api/user/login';
import { useUserStore } from '@/store/user';
import { setExpireTime, getCookie, loadAvicFont } from '@/utils/common-util';

const { proxy } = getCurrentInstance();
const i18n = useI18n();
const appStore = useAppStore();
// const multiTabState = useMultiTabStateProvider();
const dashboardRoute = {
  path: '/dashboard',
  name: 'Dashboard',
  meta: {
    icon: 'home-outlined',
    title: '首页',
    lock: true,
    hideInBreadcrumb: true,
    hideInMenu: true,
    hideChildrenInMenu: true
  }
};
const multiTabState = useMultiTabStateProvider({
  initCacheList: [
    {
      path: '/dashboard',
      route: { ...omit(dashboardRoute, ['matched']) },
      tabTitle: '首页',
      tabPath: '/dashboard',
      lock: true,
      lastActiveTime: Date.now()
    }
  ]
});
const colSize = useMediaQuery();
const isMobile = computed(() => colSize.value === 'sm' || colSize.value === 'xs');
const menuState = useMenuState(
  {
    collapsed: isMobile.value,
    openKeys: [] as string[],
    selectedKeys: [] as string[],
    isMobile
  },
  multiTabState
);

const lang = localStorage.get(STORAGE_LANG_KEY, defaultLang);
if (lang) {
  appStore.SET_LANG(lang);
}
const hashPriority = ref('high' as const);
watch(hashPriority, () => {
  location.reload();
});
export type ThemeName = '' | 'light' | 'dark' | 'compact';
const getAlgorithm = (themes: ThemeName[] = []) =>
  themes
    .filter((theme) => !!theme)
    .map((theme) => {
      if (theme === 'dark') {
        return antdTheme.darkAlgorithm;
      }
      if (theme === 'compact') {
        return antdTheme.compactAlgorithm;
      }
      return antdTheme.defaultAlgorithm;
    });
const themeConfig = computed(() => ({
  algorithm: getAlgorithm(['light']),
  token: {
    colorPrimary: appStore.primaryColor,
    colorInfo: appStore.primaryColor,
    borderRadius: 4,
    sizeUnit: 4
  }
}));
const theme = computed(() => appStore.navTheme);
const primaryColor = computed(() => appStore.primaryColor);
watch(
  theme,
  () => {
    if (theme.value === 'realDark') {
      document.getElementsByTagName('html')[0].setAttribute('data-pro-theme', 'antdv-pro-theme-dark');
    } else {
      document.getElementsByTagName('html')[0].setAttribute('data-pro-theme', 'antdv-pro-theme-light');
    }
  },
  { immediate: true }
);
watch(
  [theme, primaryColor],
  () => {
    updateTheme(theme.value === 'realDark', primaryColor.value);
  },
  { immediate: true }
);
provide('isMobile', isMobile);
provide(
  'isRealDark',
  computed(() => theme.value === 'realDark')
);
provide(MenuStateSymbol, menuState);
const locale = computed(() => i18n.getLocaleMessage(i18n.locale.value).antd as ConfigProviderProps['locale']);

// 定时刷新token定时器
// eslint-disable-next-line no-underscore-dangle
if (!window.__POWERED_BY_WUJIE__) {
  setInterval(() => {
    // 需要定时执行的代码
    const refreshTokenValue = getCookie(STORAGE_REFRESH_TOKEN_KEY);
    if (refreshTokenValue) {
      const currentTimeStamp = proxy.$dayjs().valueOf();
      const expireTime = getCookie('token_expire_time');
      const second = (expireTime - currentTimeStamp) / 1000;
      if (second < 60 * 5) {
        // token过期时间小于5分钟后开始执行刷新token
        // 过期时间小于5分钟时刷新token
        refreshToken().then((res) => {
          if (res.success) {
            const userStore = useUserStore();
            userStore.SET_TOKEN(res.data.accessToken, res.data.refreshToken);
            setExpireTime(res.data.expireTime);
          }
        });
      }
    }
    // 每分钟执行一次
  }, 1000 * 60);
}
onMounted(() => {
  loadAvicFont();
});
</script>
